<template>
  <div ref="messageContainer" class="h-100% overflow-y-auto relative">
    <div class="chat-list" v-for="(item, index) in list" :key="index">
      <!-- 靠左 message：system、assistant 类型 -->
      <div class="left-message message-item" v-if="item.type !== 'user'">
        <div class="avatar">
          <el-avatar :src="userAvatarDefaultImg" />
        </div>
        <div class="message">
          <div>
            <el-text class="time">{{ formatDate(item.createTime) }}</el-text>
          </div>
          <div class="left-text-container" ref="markdownViewRef">
            <MarkdownView class="left-text" :content="item.content" />
          </div>
          <div class="left-btns">
            <el-button class="btn-cus" link @click="copyContent(item.content)">
              <img class="btn-image" src="@/assets/ai/copy.svg" />
            </el-button>
            <el-button v-if="item.id > 0" class="btn-cus" link @click="onDelete(item.id)">
              <img class="btn-image h-17px" src="@/assets/ai/delete.svg" />
            </el-button>
          </div>
        </div>
      </div>
      <!-- 靠右 message：user 类型 -->
      <div class="right-message message-item" v-if="item.type === 'user'">
        <div class="avatar">
          <el-avatar :src="userAvatarDefaultImg" />
        </div>
        <div class="message">
          <div>
            <el-text class="time">111</el-text>
          </div>
          <div class="right-text-container">
            <div class="right-text">{{ item.content }}</div>
          </div>
          <div class="right-btns">
            <el-button class="btn-cus" link @click="copyContent(item.content)">
              <img class="btn-image" src="@/assets/ai/copy.svg" />
            </el-button>
            <el-button class="btn-cus" link @click="onDelete(item.id)">
              <img class="btn-image h-17px mr-12px" src="@/assets/ai/delete.svg" />
            </el-button>
            <el-button class="btn-cus" link @click="onRefresh(item)">
              <el-icon size="17">
                <RefreshRight />
              </el-icon>
            </el-button>
            <el-button class="btn-cus" link @click="onEdit(item)">
              <el-icon size="17">
                <Edit />
              </el-icon>
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 回到底部 -->
  <div class="to-bottom">
    <el-button :icon="ArrowDownBold" circle />
  </div>
</template>
<script setup lang="ts">
import { ArrowDownBold, Edit, RefreshRight } from "@element-plus/icons-vue";
import { formatDate } from "@/utils/formatTime";
import { nextTick, onMounted, PropType, ref, toRefs } from "vue";
import userAvatarDefaultImg from "@/assets/images/avatar.gif";
import { Chat } from "@/api/ai/chat";
import { ChatMessage } from "@/api/ai/chatmessage";
import { useMessage } from "@/hooks/useMessage";
import { useClipboard } from "@vueuse/core";

const message = useMessage();
const { copy } = useClipboard(); // 初始化 copy 到粘贴板
// 定义 props
const props = defineProps({
  conversation: {
    type: Object as PropType<Chat.ResChat>,
    required: true
  },
  list: {
    type: Array as PropType<ChatMessage.ResChatMessage[]>,
    required: true
  }
});
const { list } = toRefs(props); // 消息列表
// 判断“消息列表”滚动的位置(用于判断是否需要滚动到消息最下方)
const isScrolling = ref<boolean>(false); //用于判断用户是否在滚动
const messageContainer = ref<any>(null);
const emits = defineEmits(["onDeleteSuccess", "onRefresh", "onEdit"]); // 定义 emits
/** 滚动到底部 */
const scrollToBottom = async (isIgnore?: boolean) => {
  // 注意要使用 nextTick 以免获取不到 dom
  await nextTick();
  if (isIgnore || !isScrolling.value) {
    messageContainer.value.scrollTop = messageContainer.value.scrollHeight - messageContainer.value.offsetHeight;
  }
};
/** 刷新 */
const onRefresh = async (message: ChatMessage.ResChatMessage) => {
  emits("onRefresh", message);
};

/** 编辑 */
const onEdit = async (message: ChatMessage.ResChatMessage) => {
  emits("onEdit", message);
};

/** 复制 */
const copyContent = async content => {
  await copy(content);
  message.success("复制成功！");
};
/** 删除 */
const onDelete = async id => {
  // 删除 message
  message.success("删除成功！" + id);
  // 回调
  emits("onDeleteSuccess");
};
/** 回到顶部 */
const handlerGoTop = async () => {
  const scrollContainer = messageContainer.value;
  scrollContainer.scrollTop = 0;
};
function handleScroll() {
  const scrollContainer = messageContainer.value;
  const scrollTop = scrollContainer.scrollTop;
  const scrollHeight = scrollContainer.scrollHeight;
  const offsetHeight = scrollContainer.offsetHeight;
  if (scrollTop + offsetHeight < scrollHeight - 100) {
    // 用户开始滚动并在最底部之上，取消保持在最底部的效果
    isScrolling.value = true;
  } else {
    // 用户停止滚动并滚动到最底部，开启保持到最底部的效果
    isScrolling.value = false;
  }
}
/** 初始化 */
onMounted(async () => {
  messageContainer.value.addEventListener("scroll", handleScroll);
});
defineExpose({ scrollToBottom, handlerGoTop }); // 提供方法给 parent 调用
</script>

<style scoped lang="scss">
.message-container {
  position: relative;
  overflow-y: scroll;
}

// 中间
.chat-list {
  display: flex;
  flex-direction: column;
  padding: 0 20px;
  overflow-y: hidden;

  .message-item {
    margin-top: 50px;
  }

  .left-message {
    display: flex;
    flex-direction: row;
  }

  .right-message {
    display: flex;
    flex-direction: row-reverse;
    justify-content: flex-start;
  }

  .message {
    display: flex;
    flex-direction: column;
    margin: 0 15px;
    text-align: left;

    .time {
      line-height: 30px;
      text-align: left;
    }

    .left-text-container {
      position: relative;
      display: flex;
      flex-direction: column;
      padding: 10px 10px 5px;
      overflow-wrap: break-word;
      background-color: rgb(228 228 228 / 80%);
      border-radius: 10px;
      box-shadow: 0 0 0 1px rgb(228 228 228 / 80%);

      .left-text {
        font-size: 0.95rem;
        color: #393939;
      }
    }

    .right-text-container {
      display: flex;
      flex-direction: row-reverse;

      .right-text {
        display: inline;
        width: auto;
        padding: 10px;
        font-size: 0.95rem;
        color: #ffffff;
        overflow-wrap: break-word;
        white-space: pre-wrap;
        background-color: #267fff;
        border-radius: 10px;
        box-shadow: 0 0 0 1px #267fff;
      }
    }

    .left-btns {
      display: flex;
      flex-direction: row;
      margin-top: 8px;
    }

    .right-btns {
      display: flex;
      flex-direction: row-reverse;
      margin-top: 8px;
    }
  }

  // 复制、删除按钮
  .btn-cus {
    display: flex;
    align-items: center;
    background-color: transparent;

    .btn-image {
      height: 20px;
    }
  }

  .btn-cus:hover {
    cursor: pointer;
    background-color: #f6f6f6;
  }
}

// 回到底部
.to-bottom {
  position: absolute;
  right: 50%;
  bottom: 0;
  z-index: 1000;
}
</style>
